package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;

import java.util.ArrayList;
import java.util.List;

public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {
    private static final int BATCH_COUNT = 5;//定义每读到5条数据存一次数据库
    List<ExcelDictDTO> list = new ArrayList<>();

    private DictMapper dictMapper;

    /*传入mapper层对象*/
    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }
    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        list.add(excelDictDTO);
        if (list.size() >=BATCH_COUNT){
            saveData();
            list.clear();
        }
    }

    private void saveData() {
        dictMapper.insertBatch(list);
        //log.info("数据存储成功");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
       // log.info("善后方法执行");
        saveData();
       // log.info("剩下的数据"+list);
    }
}
